package com.hkw.servlet;

import com.hkw.model.User;
import com.hkw.service.IUserService;
import com.hkw.service.impl.UserServiceImpl;
import com.hkw.utils.DruidUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.HttpCookie;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 处理登入请求的servlet
 */
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        //实例化接口服务对象
        IUserService userService = new UserServiceImpl();
        String loginok = (String)request.getAttribute("certificate");
        System.out.println(loginok + "???");
        if(loginok != null){
            User user = (User)session.getAttribute(loginok);
            System.out.println(user);
            if(user != null && userService.login(user)==1){
                System.out.println("login成功!");
                response.sendRedirect("studentlist");
                return;
            }else{
                Cookie cookie = new Cookie("certificate","loginFail");
                cookie.setMaxAge(0);
                cookie.setPath("http://localhost:8080/homework");
                response.addCookie(cookie);
                System.out.println("login失败!???");
                response.sendRedirect("index.jsp");
                return;
            }
        }
        //获取到username和password
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User(username,password);
        System.out.println(username + " " + password);
        //调用方法
        if(userService.login(user)==1){
            System.out.println("login成功!");
            Cookie cookie = new Cookie("certificate","loginSuccess");
            cookie.setMaxAge(60*60*24*7);
            cookie.setPath("http://localhost:8080/homework");
            response.addCookie(cookie);
            session.setAttribute("loginSuccess",user);
            session.setMaxInactiveInterval(60*60*24*7);
            response.sendRedirect("studentlist");
        }else{
            System.out.println("login失败!");
            request.setAttribute("err","该用户不存在,请输入正确的信息！");
            request.getRequestDispatcher("index.jsp").forward(request,response);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
